<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户编号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="桌号" prop="tableId">
        <el-input
          v-model="queryParams.tableId"
          placeholder="请输入桌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="searchDate">
        <el-date-picker clearable
          v-model="queryParams.searchDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单号" align="center" prop="sysOrdersId" />
      <el-table-column label="下单的用户编号" align="center" prop="userId"/>
      <el-table-column label="桌号" align="center" prop="tableId" />
      <el-table-column label="菜品" align="center" prop="dishesCode" >
        <template slot-scope="scope">
          <el-popover
            placement="left"
            width="400"
            trigger="click">
            <el-table :data="scope.row.dishesList" height="350">
              <el-table-column width="100" property="dishesName" label="菜品名称"/>
              <el-table-column width="100" property="dishesImage" label="菜品图片">
                <template slot-scope="scope">
                  <image-preview :src="scope.row.dishesImage" :width="50" :height="50"/>
                </template>
              </el-table-column>
              <el-table-column width="100" property="dishesPrice" label="价格"/>
              <el-table-column width="100" property="dishesQuantity" label="菜品数量"/>
            </el-table>
            <el-button slot="reference" type="primary" size="small">查看菜品</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="套餐" align="center" prop="comboCode" >
        <template slot-scope="scope">
          <el-popover
            placement="right"
            width="400"
            trigger="click">
            <el-table :data="scope.row.comboList"  height="350">
              <el-table-column width="100" property="comboName" label="套餐名称"/>
              <el-table-column width="100" property="comboImage" label="套餐图片">
                <template slot-scope="scope">
                  <image-preview :src="scope.row.comboImage" :width="50" :height="50"/>
                </template>
              </el-table-column>
              <el-table-column width="100" property="comboDishesPrice" label="价格"/>
              <el-table-column width="100" property="comboQuantity" label="套餐数量"/>
            </el-table>
            <el-button slot="reference" type="primary" size="small">查看套餐</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="订单的付款状态" align="center" prop="ordersPriceStatus" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.ordersPriceStatus === '1'" type="warning" size="small">未付款</el-tag>
          <el-tag v-else type="success" size="small">已付款</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单的下单时间" align="center" prop="ordersCreatTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ordersCreatTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单出餐时间" align="center" prop="ordersUpdateTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.ordersStatus==='1'">
            <font color="orange">未出餐</font>
          </span>
          <span v-else>{{ parseTime(scope.row.ordersUpdateTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单的出餐状况" align="center" prop="ordersStatus" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.ordersStatus"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:orders:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:orders:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <audio id="audio">
      <source src="@/assets/audio/ggl.mp3">
    </audio>
    <!-- 添加或修改订单详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="桌号" prop="tableId">
          <el-input v-model="form.tableId" placeholder="请输入桌号" />
        </el-form-item>
        <el-form-item label="总金额" prop="ordersPrice">
          <el-input v-model="form.ordersPrice" placeholder="请输入订单的总金额" />
        </el-form-item>
        <el-form-item label="下单时间" prop="ordersCreatTime">
          <el-date-picker clearable
            v-model="form.ordersCreatTime"
            type="datetime"
            value-format="yyyy-MM-dd hh-mm-ss"
            placeholder="请选择订单的下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出餐时间" prop="ordersUpdateTime">
          <el-date-picker clearable
            v-model="form.ordersUpdateTime"
            type="datetime"
            value-format="yyyy-MM-dd hh-mm-ss"
            placeholder="请选择订单出餐时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrders,
  getOrders,
  delOrders,
  addOrders,
  updateOrders,
  listOrdersNow,
  changeOrderStatus
} from "@/api/system/orders";

export default {
  name: "Orders",
  data() {
    return {
      // 目前总的订单数
      temporaryOrdersList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单详情表格数据
      ordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        tableId: null,
        dishesCode: null,
        comboCode: null,
        ordersPrice: null,
        ordersPriceStatus: null,
        ordersCreatTime: null,
        ordersUpdateTime: null,
        ordersStatus: null,
        searchDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ordersStatus: [
          { required: true, message: "订单的出餐状况不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.Init();
  },
  methods: {
    Init(){
      this.queryParams.userId=this.$route.params.userId
      this.getList();
    },
    /** 查询订单详情列表 */
    getList() {
      this.loading = true;
      listOrders(this.queryParams).then(response => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listOrders().then(response => {
        this.temporaryOrdersList = response.rows;
      })
    },
    getListNow() {
      // 动态加载订单数据
      listOrders(this.queryParams).then(response => {
        // 如果订单的总数量多了就播放音频显示来订单了
        listOrdersNow().then(res=>{
          if (this.temporaryOrdersList.length<res.rows.length){
            document.getElementById("audio").play();
          }
          this.temporaryOrdersList=res.rows;
        })
        this.ordersList = response.rows;
        this.total = response.total;
      });
    },
    getListAlways() {
      this.loading = true;
      setInterval(this.getListNow,500)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sysOrdersId: null,
        userId: null,
        tableId: null,
        dishesCode: null,
        comboCode: null,
        ordersPrice: null,
        ordersPriceStatus: null,
        ordersCreatTime: null,
        ordersUpdateTime: null,
        ordersStatus: null,
        searchDate: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sysOrdersId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log(this.audio)
      this.reset();
      this.open = true;
      this.title = "添加订单详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sysOrdersId = row.sysOrdersId || this.ids
      getOrders(sysOrdersId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sysOrdersId != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sysOrdersIds = row.sysOrdersId || this.ids;
      this.$modal.confirm('是否确认删除订单详情编号为"' + sysOrdersIds + '"的数据项？').then(function() {
        return delOrders(sysOrdersIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    },
    handleStatusChange(row) {
      console.log(row.ordersStatus)
      let text = row.ordersStatus === "0" ? "出餐" : "撤餐";
      this.$modal.confirm('确认要"' + text + '""' + row.tableId + '"号桌吗？').then(function () {
        return changeOrderStatus(row.sysOrdersId, row.ordersStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.ordersStatus = row.ordersStatus === "0" ? "1" : "0";
      });
    },
  }
};
</script>
